﻿namespace tools.common
{
    /// <summary>
    /// 文件工具类
    /// </summary>
    public static class FileTool
    {
        /// <summary>
        /// 将文件转换为 Base64 字符串
        /// </summary>
        /// <param name="filePath">文件的完整路径</param>
        /// <returns>Base64 字符串</returns>
        public static string ToBase64(string? filePath)
        { 
            if (!File.Exists(filePath))
                throw new FileNotFoundException("找不到指定的文件", filePath);

            var bytes = File.ReadAllBytes(filePath);
            return Convert.ToBase64String(bytes);
        }

        /// <summary>
        /// 将 Base64 字符串保存为文件
        /// </summary>
        /// <param name="base64String">Base64 字符串</param>
        /// <param name="filePath">完整的存储路径</param>
        public static void Base64Save(string? base64String, string? filePath)
        {
            if (string.IsNullOrWhiteSpace(base64String))
                throw new InvalidOperationException("无效的 Base64 字符串");

            if (string.IsNullOrWhiteSpace(filePath))
                throw new InvalidOperationException("无效的文件存储路径");

            var bytes = Convert.FromBase64String(base64String);
            File.WriteAllBytes(filePath, bytes);
        }
    }
}
